const { execSync } = require('child_process')
const os = require('os')

const getFreePort = (p = 3000) => {
  let port = p
  let stdout = null
  try {
    if (os.type() === 'Windows_NT') {
      //windows
      stdout = execSync(`netstat -ano | findstr ${port}`)
      if(stdout) {
        return getFreePort(port)
      }
    } else if (os.type() === 'Darwin') {
      //mac
      stdout = execSync(`lsof -i:${port}`)
    } else if (os.type() === 'Linux') {
      //Linux
      stdout = execSync(`netstat -anp | grep ${port}`)
    }
    if (!stdout) {
      return port
    } else {
      return getFreePort()
    }
  } catch (e) {
    console.log('****************************************',e);
    return port
  }
}
module.exports = getFreePort